package com.lemurian.bankdata.action.business;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.lemurian.bankdata.dto.LogHelper;
import com.lemurian.bankdata.lite.authentication.BankDataPrincipal;
import com.lemurian.bankdata.lite.enums.UserActivityType;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.bankdata.lite.struts.Pager;
import com.lemurian.bankdata.lite.struts.PartialList;
import com.lemurian.bankdata.lite.utils.FormatData;
import com.lemurian.bankdata.lite.utils.GeneralConstant;
import com.lemurian.bankdata.lite.utils.GlobalFunction;
import com.lemurian.bankdata.report.dto.PencocokanTransaksi;
import com.lemurian.bankdata.services.ActivityLogService;
import com.lemurian.bankdata.services.ClientCertificateService;
import com.lemurian.bankdata.services.ClientService;
import com.lemurian.bankdata.services.ManagementService;
import com.lemurian.bankdata.services.ReportService;
import com.lemurian.bankdata.services.ScheduleChangesService;
import com.lemurian.bankdata.services.SignatureScheduleService;
import com.lemurian.bankdata.utils.BaseAction;
import com.lemurian.entity.Client;
import com.lemurian.entity.ClientCertificate;
import com.lemurian.entity.ScheduleChanges;
import com.lemurian.entity.SignatureSchedule;
import com.lemurian.entity.User;
import com.opensymphony.xwork2.Preparable;

public class PenjadwalanKlienAction extends BaseAction implements Preparable {

	private static final long serialVersionUID = -6214256399460505592L;

	private BankDataLogger log = BankDataLogger.getLogger(PenjadwalanKlienAction.class.getSimpleName());

	private DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	private DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	private DateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy HH:mm");
	
	private String namaKlien = "";
	private String namaDepartemen = "";
	private String tanggalTTD = "";
	
	private int id;
	private Client klien;
	
	private SignatureSchedule signatureSchedule = new SignatureSchedule();
	private List<SignatureSchedule> listSignatureSchedules = new ArrayList<SignatureSchedule>();
	
	private Date todayDate = new Date();
	private Date tomorrowDate;
	
	private List<SignatureSchedule> listJadwalToday = new ArrayList<SignatureSchedule>();
	private List<SignatureSchedule> listJadwalTomorrow = new ArrayList<SignatureSchedule>();
	
	private List<ClientCertificate> listAktaKlien = new ArrayList<ClientCertificate>();
	
	private String tanggalTerbaru = "";
	private String jamTerbaru = "";
	private String tempatTerbaru = "";
	private String alasanPembatalan = "";
			
	private List<ScheduleChanges> listHistoryJadwal = new ArrayList<ScheduleChanges>();
	
	private User user;
	private BankDataPrincipal principal;
	
	private String[] selectedRows;

	private String message = "";
	
	@Autowired private SignatureScheduleService signatureScheduleService;
	@Autowired private ClientService clientService;
	@Autowired private ClientCertificateService clientCertificateService;
	@Autowired private ScheduleChangesService scheduleChangesService; 
	@Autowired private ManagementService kepengurusanService;
	@Autowired private ReportService reportService;
	
	private String downloadContentType;
	private InputStream inputStream;
	private String downloadFileName;
	
	private Map parameters;
	
	private static final String FILE_LOCATION_1 = ServletActionContext.getServletContext().getRealPath("jasper/pencocokan_trx_hari_ini.jasper");
	private static final String FILE_LOCATION_2 = ServletActionContext.getServletContext().getRealPath("jasper/pencocokan_trx_hari_esok.jasper");
	private static final String IMAGE_LOCATION = ServletActionContext.getServletContext().getRealPath("");
	
	@Autowired 
	private ActivityLogService userActivityLogService;
	private LogHelper userActivityLog;
	
	@Override
	public void prepare() throws Exception {
		principal = (BankDataPrincipal) getSession().get(GeneralConstant.USER_PRINCIPAL);
		user = principal.getUser();
		
		log.sInfo("get signature id [%s]", id);
        if (id > 0) {
        	signatureSchedule = signatureScheduleService.findById(id);
        }
	}

	@Override
	@SkipValidation
	public String list() {
		log.info("list jadwal tandatangan klien");
		setPreviousPage(GeneralConstant.LIST);
		try {
			Date lo = null;
			Date hi = null;
			if (tanggalTTD != null && !tanggalTTD.equalsIgnoreCase("")) {
				String startTime = tanggalTTD + " 00:00";
				String endTime = tanggalTTD + " 23:59";
				
				lo = sdf2.parse(startTime);
				hi = sdf2.parse(endTime);
				
				System.out.println("sTime : " + startTime);
				System.out.println("endTime : " + endTime);
				System.out.println("lo : " + lo);
				System.out.println("hi : " + hi);
			}
			PartialList<SignatureSchedule> partialList = signatureScheduleService.findSchedule(getStart(), getCount(),
					getAscDesc().equalsIgnoreCase("desc") ? Order.desc(getOrderBy().length() > 0 ? getOrderBy() : "signatureDate") : Order.asc(getOrderBy().length() > 0 ? getOrderBy() : "signatureDate"),
					lo != null && hi != null ? Restrictions.between("signatureDate", lo, hi) : Restrictions.ne("id", new Integer(-1)),
					namaKlien != null && !namaKlien.equalsIgnoreCase("") ? Restrictions.ilike("debitur.name", namaKlien, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
					namaDepartemen != null && !namaDepartemen.equalsIgnoreCase("") ? Restrictions.ilike("department.name", namaDepartemen, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1))
					);

            listSignatureSchedules = partialList.getList();
            log.sInfo("found [%s] jadwal ", listSignatureSchedules.size());
            for (SignatureSchedule ss : listSignatureSchedules) {
				List<ClientCertificate> listClientCertificate = clientCertificateService.findByCriteria(Order.asc("id"), Restrictions.eq("client", ss.getClient()));
				log.sInfo("Client cert size : %s", listClientCertificate.size());
				ss.getClient().setClientCertificates(listClientCertificate);
			}
            
            setPager(Pager.generatePager(getStart(), getCount(), partialList.getTotal()));
            setPagerItem(Pager.generatePagerItem(getStart(), getCount(), partialList.getTotal()));

            partialList = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
        setMappedRequest(GeneralConstant.SAVE);
        return SUCCESS;
	}
	
	// ==================================================================================================================================
	// ===================== JADWAL HARI INI PAGE =======================================================================================
	
	public String listToday() {
		log.info("list jadwal tandatangan klien today");
		setPreviousPage(GeneralConstant.LIST);
		try {
			Date now = new Date();
			String startTime = df.format(now) + " 00:00";
			String endTime = df.format(now) + " 23:59";
			
			Date lo = sdf.parse(startTime);
			Date hi = sdf.parse(endTime);
			
			System.out.println("sTime : " + startTime);
			System.out.println("endTime : " + endTime);
			System.out.println("lo : " + lo);
			System.out.println("hi : " + hi);
			
			PartialList<SignatureSchedule> partialListToday = signatureScheduleService.findSchedule(getStart(), getCount(),
					getAscDesc().equalsIgnoreCase("desc") ? Order.desc(getOrderBy().length() > 0 ? getOrderBy() : "signatureDate") : Order.asc(getOrderBy().length() > 0 ? getOrderBy() : "signatureDate"),
					Restrictions.between("signatureDate", lo, hi),
					namaKlien != null && !namaKlien.equalsIgnoreCase("") ? Restrictions.ilike("debitur.name", namaKlien, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
					namaDepartemen != null && !namaDepartemen.equalsIgnoreCase("") ? Restrictions.ilike("department.name", namaDepartemen, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1))
                    );

            listJadwalToday = partialListToday.getList();
            log.sInfo("found [%s] jadwal for today", listJadwalToday.size());
            for (SignatureSchedule ss : listJadwalToday) {
				List<ClientCertificate> listClientCertificate = clientCertificateService.findByCriteria(Order.asc("id"), Restrictions.eq("client", ss.getClient()));
				log.sInfo("Client cert size : %s", listClientCertificate.size());
				ss.getClient().setClientCertificates(listClientCertificate);
			}
            
            setPager(Pager.generatePager(getStart(), getCount(), partialListToday.getTotal()));
            setPagerItem(Pager.generatePagerItem(getStart(), getCount(), partialListToday.getTotal()));

            partialListToday = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
        setMappedRequest(GeneralConstant.SAVE);
        return SUCCESS;
	}

	public String saveToday() {
		log.info("on sudah tanda tangan clicked ..");
		try {
			// Set sudah tanda tangan untuk jadwal hari ini
			log.sInfo("Total Checked [%s]", selectedRows.length);
			for (int i = 0; i < selectedRows.length; i++) {
				log.sInfo("Rows check [%s]", selectedRows[i]);
				int signId = Integer.parseInt(GlobalFunction.decodeParameter(selectedRows[i]));
				signatureSchedule = signatureScheduleService.findById(signId);
				if (signatureSchedule != null) {
					log.sInfo("Schedule Record was found [%s]", signatureSchedule.getId());
				} else {
					// Harusnya ga mungkin
					log.info("init new object <-- harusnya ga mungkin");
					signatureSchedule = new SignatureSchedule();
				}
				
				signatureSchedule.setSignatureStatus(true);
				// basic info
				signatureSchedule.setUpdateDate(new Timestamp(System.currentTimeMillis()));
				signatureSchedule.setUpdateBy(user.getLoginId());
				
				try {
					signatureScheduleService.save(signatureSchedule);
					
					userActivityLog = new LogHelper(user, UserActivityType.UPDATE_SCHEDULE_SIGNATURE);
					
		            try {
		                log.sInfo(" :: User [%s:%s] is successfully updated schedule signature of [%s]", user.getId(), user.getName(), signatureSchedule.getClient().getDebitur().getName());

		                //check if activity is success
		                userActivityLog.setStatus(LogHelper.SUCCESS_ACTIVITY);
		            } catch (Exception e) {
		                log.sInfo(" :: Error was raised when User [%s:%s] updated schedule signature of [%s]", user.getId(), user.getName(), signatureSchedule.getClient().getDebitur().getName());
		                
		                //set activity log status into failed
		                userActivityLog.setStatus(LogHelper.FAILED_ACTIVITY);
		                userActivityLog.setErrorMsg(e.getMessage());
		            }
		            //save activity log
		            userActivityLog.setSessionId(ServletActionContext.getRequest().getSession().getId());
		            userActivityLog.getAdditionalParams().add(signatureSchedule.getClient().getDebitur().getName());
		            userActivityLogService.saveUserActivity(userActivityLog);
				} catch (Exception e) {
					e.printStackTrace();
				    message = "Maaf terjadi kesalahan, message : "+e.getMessage();
		            addCustomActionError(message);
		    		setMappedRequestFullPath("/PenjadwalanKlienAction_listToday.do");
		    		return GeneralConstant.REDIRECT;
				}
				message = "Data klien berhasil disimpan";
	            addCustomActionMessage(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		    message += "Maaf terjadi kesalahan, message : "+e.getMessage();
            addActionError(message);
		}
		setMappedRequestFullPath("/PenjadwalanKlienAction_listToday.do");
		return GeneralConstant.REDIRECT;
	}
	
	// ==================================================================================================================================
	// ================= JADWAL TOMORROW PAGE ===========================================================================================
	
	public String listTomorrow() {
		log.info("list jadwal tandatangan klien esok hari");
		setPreviousPage("listTomorrow");
		try {
			
			Date now = new Date();

			Calendar calendar = Calendar.getInstance();
			calendar.setTime(now);
			calendar.add(Calendar.DATE, 1);
			
			tomorrowDate = calendar.getTime();
			
			String startTime = df.format(calendar.getTime()) + " 00:00";
			String endTime = df.format(calendar.getTime()) + " 23:59";
			
			Date lo = sdf.parse(startTime);
			Date hi = sdf.parse(endTime);
			
			System.out.println("sTime : " + startTime);
			System.out.println("endTime : " + endTime);
			System.out.println("lo : " + lo);
			System.out.println("hi : " + hi);
			
			PartialList<SignatureSchedule> partialListTomorrow = signatureScheduleService.findSchedule(getStart(), getCount(),
					getAscDesc().equalsIgnoreCase("desc") ? Order.desc(getOrderBy().length() > 0 ? getOrderBy() : "signatureDate") : Order.asc(getOrderBy().length() > 0 ? getOrderBy() : "signatureDate"),
					Restrictions.between("signatureDate", lo, hi),
					//Restrictions.eq("signatureStatus", false),
					namaKlien != null && !namaKlien.equalsIgnoreCase("") ? Restrictions.ilike("debitur.name", namaKlien, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1))
                    );

            listJadwalTomorrow = partialListTomorrow.getList();
            log.sInfo("found [%s] jadwal for tomorrow", listJadwalTomorrow.size());
            for (SignatureSchedule ss : listJadwalTomorrow) {
				List<ClientCertificate> listClientCertificate = clientCertificateService.findByCriteria(Order.asc("id"), Restrictions.eq("client", ss.getClient()));
				log.sInfo("Client cert size : %s", listClientCertificate.size());
				ss.getClient().setClientCertificates(listClientCertificate);
			}
            
            setPager(Pager.generatePager(getStart(), getCount(), partialListTomorrow.getTotal()));
            setPagerItem(Pager.generatePagerItem(getStart(), getCount(), partialListTomorrow.getTotal()));

            partialListTomorrow = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
        setMappedRequest("saveTomorrow");
        return SUCCESS;
	}
	
	public String saveTomorrow() {
		log.info("on sudah tanda tangan clicked ..");
		try {
			// Set sudah tanda tangan untuk jadwal hari ini
			log.sInfo("Total Checked [%s]", selectedRows.length);
			for (int i = 0; i < selectedRows.length; i++) {
				log.sInfo("Rows check [%s]", selectedRows[i]);
				int signId = Integer.parseInt(GlobalFunction.decodeParameter(selectedRows[i]));
				signatureSchedule = signatureScheduleService.findById(signId);
				if (signatureSchedule != null) {
					log.sInfo("Schedule Record was found [%s]", signatureSchedule.getId());
				} else {
					// Harusnya ga mungkin
					log.info("init new object <-- harusnya ga mungkin");
					signatureSchedule = new SignatureSchedule();
				}
				signatureSchedule.setSignatureStatus(true);
				// basic info
				signatureSchedule.setUpdateDate(new Timestamp(System.currentTimeMillis()));
				signatureSchedule.setUpdateBy(user.getLoginId());
				try {
					signatureScheduleService.save(signatureSchedule);
					
					userActivityLog = new LogHelper(user, UserActivityType.UPDATE_SCHEDULE_SIGNATURE);
					
		            try {
		                log.sInfo(" :: User [%s:%s] is successfully updated schedule signature of [%s]", user.getId(), user.getName(), signatureSchedule.getClient().getDebitur().getName());

		                //check if activity is success
		                userActivityLog.setStatus(LogHelper.SUCCESS_ACTIVITY);
		            } catch (Exception e) {
		                log.sInfo(" :: Error was raised when User [%s:%s] updated schedule signature of [%s]", user.getId(), user.getName(), signatureSchedule.getClient().getDebitur().getName());
		                
		                //set activity log status into failed
		                userActivityLog.setStatus(LogHelper.FAILED_ACTIVITY);
		                userActivityLog.setErrorMsg(e.getMessage());
		            }
		            //save activity log
		            userActivityLog.setSessionId(ServletActionContext.getRequest().getSession().getId());
		            userActivityLog.getAdditionalParams().add(signatureSchedule.getClient().getDebitur().getName());
		            userActivityLogService.saveUserActivity(userActivityLog);
				} catch (Exception e) {
					e.printStackTrace();
				    message = "Maaf terjadi kesalahan, message : "+e.getMessage();
		            addCustomActionError(message);
		    		setMappedRequestFullPath("/PenjadwalanKlienAction_listTomorrow.do");
		    		return GeneralConstant.REDIRECT;
				}
				message = "Data klien berhasil disimpan";
	            addCustomActionMessage(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		    message += "Maaf terjadi kesalahan, message : "+e.getMessage();
            addActionError(message);
		}
		setMappedRequestFullPath("/PenjadwalanKlienAction_listTomorrow.do");
		return GeneralConstant.REDIRECT;
	}
		
	
	// ==================================================================================================================================
	// ===================== UBAH JADWAL PAGE ===========================================================================================
	
	public String ubahJadwal() {
		log.info("on ubah jadwal page");
		setMappedRequest("saveUbahJadwal");
		try {
			if (id > 0) {
				log.info("querying history jadwal for klien : " + signatureSchedule.getClient().getId());
				listHistoryJadwal = scheduleChangesService.findByCriteria(Order.desc("signatureDate"), Restrictions.eq("client", signatureSchedule.getClient()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String saveUbahJadwal() {
		log.info("on saving ubah jadwal");
		try {
			if (signatureSchedule.getSignatureDate() != null) {
				if (alasanPembatalan == null || alasanPembatalan.equalsIgnoreCase("")) {
					String msg = "Berikan alasan pembatalan";
					log.info(msg);
					addCustomActionError(msg);
					setPreviousPage("ubahJadwal");
					return INPUT;
				}
				
				ScheduleChanges jadwalSebelumnya = new ScheduleChanges();
				jadwalSebelumnya.setClient(signatureSchedule.getClient());
				jadwalSebelumnya.setSignatureDate(signatureSchedule.getSignatureDate());
				jadwalSebelumnya.setCancelationReason(alasanPembatalan);
				jadwalSebelumnya.setCreateBy(user.getLoginId());
				jadwalSebelumnya.setCreateDate(new Timestamp(System.currentTimeMillis()));
				
				log.sInfo("adding history pembatalan tgl [%s]", jadwalSebelumnya.getSignatureDate());
				scheduleChangesService.save(jadwalSebelumnya);	
			}
			
			log.info("save jadwal terbaru");
			if (tanggalTerbaru != null && tanggalTerbaru.trim().length() > 0 && jamTerbaru != null && jamTerbaru.trim().length() > 0) {
				log.sInfo("jadwal tandatangan [%s]", tanggalTerbaru + " " + jamTerbaru);
				String tgl = tanggalTerbaru + " " + jamTerbaru;
				System.out.println("tgl : " + tgl);
				DateFormat dflocal = new SimpleDateFormat("dd-MM-yyyy HH:mm");
				System.out.println("tgl date format : " + dflocal.parse(tgl));
				signatureSchedule.setSignatureDate(dflocal.parse(tgl));
				log.sInfo("jadwal tandatangan sekarang [%s]", signatureSchedule.getSignatureDate());
			} else {
				String msg = "Tanggal dan jam harus diisi";
				log.info(msg);
				addCustomActionError(msg);
				setPreviousPage("ubahJadwal");
				return INPUT;
			}
			
			signatureSchedule.setPlace(tempatTerbaru);
			signatureScheduleService.save(signatureSchedule);
			addCustomActionMessage("Jadwal Berhasil diubah menjadi tanggal " + sdf.format(signatureSchedule.getSignatureDate()));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		setMappedRequestFullPath("/PenjadwalanKlienAction_list.do");
		return GeneralConstant.REDIRECT;
	}
	
	@SuppressWarnings({ "unchecked", "deprecation" })
	public String pdfHariIni() {
		
		try {
			parameters = new HashMap();
			
			parameters.put("image", IMAGE_LOCATION);
			parameters.put("tanggal", FormatData.dateFormatDay.format(new Date()));
			parameters.put("namaDebitur", namaKlien);
			parameters.put("accountOfficer", "Udah Ga Ada Variablenya");
			parameters.put("divisi", user.getDepartment() != null ? user.getDepartment().getName() : "");
			
			Date now = new Date();
			String startTime = df.format(now) + " 00:00";
			String endTime = df.format(now) + " 23:59";
			
			List<PencocokanTransaksi> list = reportService.listPencocokanTransaksi(getOrderBy(), getAscDesc(), namaKlien, null, sdf.parse(startTime), sdf.parse(endTime));
			
			JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);
			
			JasperReport jasperReport = (JasperReport) JRLoader.loadObject(FILE_LOCATION_1);
			
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
			
			byte[] pdfStream = JasperExportManager.exportReportToPdf(jasperPrint);
			
			inputStream = new ByteArrayInputStream(pdfStream);
			downloadContentType = "application/vnd.pdf";
			downloadFileName = "JadwalTTDHariIni.pdf";
			
		} catch (Throwable t) {
			t.printStackTrace();
		}
		
		return "download";
	}
	
	public String excelHariIni() {
		
		try {
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			WritableWorkbook workbook = Workbook.createWorkbook(baos);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			WritableCellFormat integerFormat = new WritableCellFormat (NumberFormats.INTEGER); 
			
			int start = 5;
			
			Label label = null;
			
			label = new Label(0,0,"Pencocokan Transaksi Hari Ini");
			sheet.addCell(label);
			label = new Label(0,1,"Pertanggal");
			sheet.addCell(label);
			label = new Label(0,2,"Nama Debitur");
			sheet.addCell(label);
			label = new Label(0,3,"Account Officer");
			sheet.addCell(label);
			
			label = new Label(0,start,"No");
			sheet.addCell(label);
			label = new Label(1,start,"No Form");
			sheet.addCell(label);
			label = new Label(2,start,"Debitur");
			sheet.addCell(label);
			label = new Label(3,start,"Jenis Akta");
			sheet.addCell(label);
			label = new Label(4,start,"Wilayah");
			sheet.addCell(label);
			label = new Label(5,start,"Klien");
			sheet.addCell(label);
			label = new Label(6,start,"Account Officer");
			sheet.addCell(label);
			label = new Label(7,start,"TBO Dokumen");
			sheet.addCell(label);
			
			start++;
			
			Date now = new Date();
			String startTime = df.format(now) + " 00:00";
			String endTime = df.format(now) + " 23:59";
			
			List<PencocokanTransaksi> list = reportService.listPencocokanTransaksi(getOrderBy(), getAscDesc(), namaKlien, null, sdf.parse(startTime), sdf.parse(endTime));
			
			int i=1;
			
			Label _pertanggal = new Label(1, 1, FormatData.dateFormatDay.format(new Date()));
			sheet.addCell(_pertanggal);
			Label _namaDebitur = new Label(1, 2, namaKlien);
			sheet.addCell(_namaDebitur);
			Label _accountOfficer = new Label(1, 3, "Udah Ga Ada Variablenya");
			sheet.addCell(_accountOfficer);
			
			for(PencocokanTransaksi data : list) {
				// No
				jxl.write.Number no = new jxl.write.Number(0, start, i++, integerFormat);
				sheet.addCell(no);
				//No Form
				Label noForm = new Label(1, start, String.valueOf(data.getNoForm()));
				sheet.addCell(noForm);
				//Debitur
				Label debitur = new Label(2, start, data.getDebitur());
				sheet.addCell(debitur);
				//Jenis Akta
				Label jenisAkta = new Label(3, start, data.getJenisAkta());
				sheet.addCell(jenisAkta);
				//Wilayah
				Label wilayah = new Label(4, start, data.getWilayah());
				sheet.addCell(wilayah);
				//Klien
				Label klien = new Label(5, start, data.getKlien());
				sheet.addCell(klien);
				//Account Officer
				Label ao = new Label(6, start, data.getAccountOfficer());
				sheet.addCell(ao);
				//TBO
				Label tbo = new Label(7, start, data.getTboDokumen());
				sheet.addCell(tbo);
				
				start++;
			}
			
			workbook.write();
			workbook.close();
			
			inputStream = new ByteArrayInputStream(baos.toByteArray());
			downloadContentType = "application/vnd.ms-excel";
			downloadFileName = "JadwalTTDHariIni.xls";
			baos.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "download";
	}
	
	@SuppressWarnings({ "unchecked", "deprecation" })
	public String pdfHariEsok() {
		
		try {
			parameters = new HashMap();
			
			parameters.put("image", IMAGE_LOCATION);
			parameters.put("namaDebitur", namaKlien);
			parameters.put("accountOfficer", "Udah Ga Ada Variablenya");
			parameters.put("divisi", user.getDepartment() != null ? user.getDepartment().getName() : "");
			
			Date now = new Date();

			Calendar calendar = Calendar.getInstance();
			calendar.setTime(now);
			calendar.add(Calendar.DATE, 1);
			
			tomorrowDate = calendar.getTime();
			parameters.put("tanggal", FormatData.dateFormatDay.format(tomorrowDate));
			
			String startTime = df.format(calendar.getTime()) + " 00:00";
			String endTime = df.format(calendar.getTime()) + " 23:59";
			
			List<PencocokanTransaksi> list = reportService.listPencocokanTransaksi(getOrderBy(), getAscDesc(), namaKlien, null, sdf.parse(startTime), sdf.parse(endTime));
			
			JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);
			
			JasperReport jasperReport = (JasperReport) JRLoader.loadObject(FILE_LOCATION_2);
			
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
			
			byte[] pdfStream = JasperExportManager.exportReportToPdf(jasperPrint);
			
			inputStream = new ByteArrayInputStream(pdfStream);
			downloadContentType = "application/vnd.pdf";
			downloadFileName = "JadwalTTDHariEsok.pdf";
			
		} catch (Throwable t) {
			t.printStackTrace();
		}
		
		return "download";
	}
	
	public String excelHariEsok() {
		
		try {
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			WritableWorkbook workbook = Workbook.createWorkbook(baos);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			WritableCellFormat integerFormat = new WritableCellFormat (NumberFormats.INTEGER); 
			
			int start = 5;
			
			Label label = null;
			
			label = new Label(0,0,"Pencocokan Transaksi Hari Esok");
			sheet.addCell(label);
			label = new Label(0,1,"Pertanggal");
			sheet.addCell(label);
			label = new Label(0,2,"Nama Debitur");
			sheet.addCell(label);
			label = new Label(0,3,"Account Officer");
			sheet.addCell(label);
			
			label = new Label(0,start,"No");
			sheet.addCell(label);
			label = new Label(1,start,"No Form");
			sheet.addCell(label);
			label = new Label(2,start,"Debitur");
			sheet.addCell(label);
			label = new Label(3,start,"Jenis Akta");
			sheet.addCell(label);
			label = new Label(4,start,"Wilayah");
			sheet.addCell(label);
			label = new Label(5,start,"Klien");
			sheet.addCell(label);
			label = new Label(6,start,"Account Officer");
			sheet.addCell(label);
			label = new Label(7,start,"TBO Dokumen");
			sheet.addCell(label);
			
			start++;
			
			Date now = new Date();

			Calendar calendar = Calendar.getInstance();
			calendar.setTime(now);
			calendar.add(Calendar.DATE, 1);
			
			tomorrowDate = calendar.getTime();
			
			String startTime = df.format(calendar.getTime()) + " 00:00";
			String endTime = df.format(calendar.getTime()) + " 23:59";
			
			List<PencocokanTransaksi> list = reportService.listPencocokanTransaksi(getOrderBy(), getAscDesc(), namaKlien, null, sdf.parse(startTime), sdf.parse(endTime));
			
			int i=1;
			
			Label _pertanggal = new Label(1, 1, FormatData.dateFormatDay.format(new Date()));
			sheet.addCell(_pertanggal);
			Label _namaDebitur = new Label(1, 2, namaKlien);
			sheet.addCell(_namaDebitur);
			Label _accountOfficer = new Label(1, 3, "Udah Ga Ada Variablenya");
			sheet.addCell(_accountOfficer);
			
			for(PencocokanTransaksi data : list) {
				// No
				jxl.write.Number no = new jxl.write.Number(0, start, i++, integerFormat);
				sheet.addCell(no);
				//No Form
				Label noForm = new Label(1, start, String.valueOf(data.getNoForm()));
				sheet.addCell(noForm);
				//Debitur
				Label debitur = new Label(2, start, data.getDebitur());
				sheet.addCell(debitur);
				//Jenis Akta
				Label jenisAkta = new Label(3, start, data.getJenisAkta());
				sheet.addCell(jenisAkta);
				//Wilayah
				Label wilayah = new Label(4, start, data.getWilayah());
				sheet.addCell(wilayah);
				//Klien
				Label klien = new Label(5, start, data.getKlien());
				sheet.addCell(klien);
				//Account Officer
				Label ao = new Label(6, start, data.getAccountOfficer());
				sheet.addCell(ao);
				//TBO
				Label tbo = new Label(7, start, data.getTboDokumen());
				sheet.addCell(tbo);
				
				start++;
			}
			
			workbook.write();
			workbook.close();
			
			inputStream = new ByteArrayInputStream(baos.toByteArray());
			downloadContentType = "application/vnd.ms-excel";
			downloadFileName = "JadwalTTDHariEsok.xls";
			baos.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "download";
	}
	
	@Override
	@SkipValidation
	public String add() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@SkipValidation
	public String edit() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String update() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@SkipValidation
	public String detail() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@SkipValidation
	public String delete() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String save() {
		// TODO Auto-generated method stub
		return null;
	}
	
	// ==============================================================================================================================
	// ====================== GETTER SETTER =========================
	// ==============================================================================================================================
	
	public String getNamaKlien() {
		return namaKlien;
	}

	public void setNamaKlien(String namaKlien) {
		this.namaKlien = namaKlien;
	}

	public String getTanggalTTD() {
		return tanggalTTD;
	}

	public void setTanggalTTD(String tanggalTTD) {
		this.tanggalTTD = tanggalTTD;
	}

	public int getId() {
		return id;
	}

	public void setId(String id) {
		System.out.println("id : " + id);
		int id_ = 0;
		if(id != null && !id.equalsIgnoreCase("0")) {
			id = GlobalFunction.decodeParameter(id);
	        id_ = Integer.parseInt(id);
		}
        this.id = id_;
	}

	public Client getKlien() {
		return klien;
	}

	public void setKlien(Client klien) {
		this.klien = klien;
	}

	public SignatureSchedule getSignatureSchedule() {
		return signatureSchedule;
	}

	public void setSignatureSchedule(SignatureSchedule signatureSchedule) {
		this.signatureSchedule = signatureSchedule;
	}

	public List<SignatureSchedule> getListSignatureSchedules() {
		return listSignatureSchedules;
	}

	public void setListSignatureSchedules(
			List<SignatureSchedule> listSignatureSchedules) {
		this.listSignatureSchedules = listSignatureSchedules;
	}

	public Date getTodayDate() {
		return todayDate;
	}

	public void setTodayDate(Date todayDate) {
		this.todayDate = todayDate;
	}

	public Date getTomorrowDate() {
		return tomorrowDate;
	}

	public void setTomorrowDate(Date tomorrowDate) {
		this.tomorrowDate = tomorrowDate;
	}

	public List<SignatureSchedule> getListJadwalToday() {
		return listJadwalToday;
	}

	public void setListJadwalToday(List<SignatureSchedule> listJadwalToday) {
		this.listJadwalToday = listJadwalToday;
	}

	public List<SignatureSchedule> getListJadwalTomorrow() {
		return listJadwalTomorrow;
	}

	public void setListJadwalTomorrow(List<SignatureSchedule> listJadwalTomorrow) {
		this.listJadwalTomorrow = listJadwalTomorrow;
	}

	public List<ClientCertificate> getListAktaKlien() {
		return listAktaKlien;
	}

	public void setListAktaKlien(List<ClientCertificate> listAktaKlien) {
		this.listAktaKlien = listAktaKlien;
	}

	public String getTanggalTerbaru() {
		return tanggalTerbaru;
	}

	public void setTanggalTerbaru(String tanggalTerbaru) {
		this.tanggalTerbaru = tanggalTerbaru;
	}

	public String getJamTerbaru() {
		return jamTerbaru;
	}

	public void setJamTerbaru(String jamTerbaru) {
		this.jamTerbaru = jamTerbaru;
	}

	public String getTempatTerbaru() {
		return tempatTerbaru;
	}

	public void setTempatTerbaru(String tempatTerbaru) {
		this.tempatTerbaru = tempatTerbaru;
	}

	public String getAlasanPembatalan() {
		return alasanPembatalan;
	}

	public void setAlasanPembatalan(String alasanPembatalan) {
		this.alasanPembatalan = alasanPembatalan;
	}

	public List<ScheduleChanges> getListHistoryJadwal() {
		return listHistoryJadwal;
	}

	public void setListHistoryJadwal(List<ScheduleChanges> listHistoryJadwal) {
		this.listHistoryJadwal = listHistoryJadwal;
	}

	public DateFormat getDf() {
		return df;
	}

	public void setDf(DateFormat df) {
		this.df = df;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getDownloadFileName() {
		return downloadFileName;
	}

	public void setDownloadFileName(String downloadFileName) {
		this.downloadFileName = downloadFileName;
	}

	public String[] getSelectedRows() {
		return selectedRows;
	}

	public void setSelectedRows(String[] selectedRows) {
		this.selectedRows = selectedRows;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getNamaDepartemen() {
		return namaDepartemen;
	}

	public void setNamaDepartemen(String namaDepartemen) {
		this.namaDepartemen = namaDepartemen;
	}

	
}
